﻿package com.thorqq.magictimer.misc;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import com.thorqq.magictimer.util.Util;

import android.content.Context;

public class FileOperator
{
    final public static String musicEnd[] = { "ogg", "mp3", "mid", "mp4", "m4a", "aac", "ts",
        "3gp", "flac", "xmf", "mxmf", "rtttl", "rtx", "ota", "imy", "mkv", "wav" };

    /**
     * @param context
     *            上下文对象
     * @param path
     *            目录路径
     * @param fs1
     *            文件夹排序方式
     * @param fs2
     *            文件排序方式
     * @param firstSort
     *            文件和文件夹谁排先
     * @return ArrayList
     */
    public static int listMusicFiles(Context context, File path, List<File> fileList)
    {
        if(fileList == null)
        {
            fileList = new ArrayList<File>();
        }
        fileList.clear();
        
        
        Mp3FileNameFilter filenameFilter = new Mp3FileNameFilter();  
        for(int i = 0; i < musicEnd.length; i++)
        {
            filenameFilter.addType(musicEnd[i]);
        }
        
        Util.log("path: " + path);
        File[] files = path.listFiles(filenameFilter);
        if(files == null)
        {
            return 0;
        }

        // 排序
        for (File f : files)
        {
            fileList.add(f);
        }
        Collections.sort(fileList);

        return fileList.size();

    }

    static public class Mp3FileNameFilter implements FilenameFilter {

        Vector<String> mTypes;

        /**
         * 构造一个Mp3FileNameFilter对象，其指定文件类型为空。
         */
        protected Mp3FileNameFilter() {
            mTypes = new Vector<String>();
        }

        /**
         * 构造一个Mp3FileNameFilter对象，具有指定的文件类型。
         * @param types
         */
        protected Mp3FileNameFilter(Vector<String> types) {
            super();
            this.mTypes = types;
        }

        @Override
        public boolean accept(File dir, String filename) 
        {
            for(int i = 0; i < this.mTypes.size(); i++)
            {
                boolean xx = (new File(dir, filename)).isDirectory();
                if(xx)
                {
                    return true;
                }
                
                if( filename.endsWith(this.mTypes.get(i)))
                {
                    return true;
                }
            }
            return false;
        }
        
        /**
         * 添加指定类型的文件。
         * 
         * @param type  将添加的文件类型，如".mp3"。
         */
        public void addType(String type) {
            mTypes.add(type);
        }
    }
}